# coding:utf-8
"""
Author: r.xw
Date: 2024/1/4
File: utils.py
"""
import os
import random
import string
from io import BytesIO

from PIL import Image, ImageFont, ImageDraw


class ImageCode:
    @staticmethod
    def get_text():
        lst = random.sample(string.ascii_letters + string.digits, 5)
        return ''.join(lst)

    def rand_color(self):
        # r
        red = random.randint(0, 255)
        green = random.randint(0, 255)
        blue = random.randint(0, 255)
        return red, green, blue

    def draw_lines(self, draw, num, width, height):
        for i in range(num):
            x1 = random.randint(0, width / 2)
            y1 = random.randint(0, height)
            x2 = random.randint(width / 2, width)
            y2 = random.randint(0, height)
            draw.line(((x1, y1), (x2, y2)), fill='black', width=2)

    def draw_verify_code(self):
        code = self.get_text()
        # 设置图片宽高
        width, height = 100, 40
        im = Image.new('RGB', (width, height), 'white')
        font = ImageFont.truetype(font='../resource/font/arial.ttf', size=30)
        # im.show()
        draw = ImageDraw.Draw(im)
        # 绘制字符串
        for i in range(4):
            draw.text(
                (
                    random.randint(1, 5) + 25 * i,
                    random.randint(1, 5)
                ),
                text=code[i],
                fill=self.rand_color(),
                font=font

            )
        self.draw_lines(draw, 3, width, height)
        # im.show()
        return im, code

    def get_code(self):
        image, code = self.draw_verify_code()
        buf = BytesIO()
        image.save(buf, 'jpeg')
        image_b_string = buf.getvalue()
        return code, image_b_string


if __name__ == '__main__':
    image_code = ImageCode()
    # image_code.draw_verify_code()
    code, image = image_code.get_code()
    print(code, image)
